//
//  SNShopPageViewController.m
//  app
//
//  Created by 王少宁 on 15/6/29.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//  商城首页

#import "SNShopPageViewController.h"
#import "SNShopPageDataManager.h"
#import "HZGoodsSalesViewController.h"
#import "HZGoodsDetailViewController.h"
#import "HZMallGoodsListViewController.h"
#import "HZMallHomeSearchNaviBar.h"
#import "HZMallSearchViewController.h"
#import "SNWXVoiceTestViewController.h"
#import "HZMallGoodsTemaiListViewController.h"

#import "SNNavigationBar.h"
#import "SNBrandsadCell.h"
#import "SNActivitiesIconCell.h"
#import "SNNoticesListCell.h"
#import "SNThemeActsListCell.h"
#import "SNActivitiesListCell.h"
#import "SNHotProductCell.h"
#import "HDMyCommunityController.h"
#import "HDChatLIstController.h"                       //聊天
#import "HZMallFindViewController.h"        //分类
#import "HDContentTenementController.h"     //联系物业
#import "SNSystemNotifyController.h"        //系统通知
#import "SNAllNotifyViewController.h"

#define kRefreshSelfTime (10*60)

@interface SNShopPageViewController ()<SNShopPageItemPushDelegate,SNMoreBtnInHeaderViewClickDelegate,UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>

@property (nonatomic, assign) int viewWillAppearCount;
@property (nonatomic, retain) UIButton * navigationBtn;
@property (nonatomic, retain) UITableView * myTableView;
@property (nonatomic, retain) SNUniteUrl * uniteUrl;
@property (nonatomic, retain) SNShopPageDataManager * manager;
@property (nonatomic, retain) SNShopPageHttpResult * result;
/** 安全timer -wirte by khzliu */
@property (strong, nonatomic) UBTargetTimer *safetyTimer;

@end


@implementation SNShopPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.uniteUrl = [SNUniteUrl shareUniteUrl];
    self.result = [[SNShopPageHttpResult alloc] initWithTarget:self action:@selector(reloadShopPageData:)];
    self.manager = [[SNShopPageDataManager alloc] initWithResult:self.result];

    [self createTabelView];
    [self createNavigationBar];
    
    self.viewWillAppearCount = 0;
    self.safetyTimer = [[UBTargetTimer alloc] initWithInterval:0.3f repeats:YES];
    self.safetyTimer.caller = [UBTargetCaller of:self action:@selector(cellTimeChange)];
    [self.safetyTimer fire];
}

- (void)createNavigationBar
{
    SNNavigationBar * navigationBarView = [[SNNavigationBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.navigationAndStatusBarHeight)];
    navigationBarView.backgroundColor = [UIColor whiteColor];
    
    _navigationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_navigationBtn setTitleColor:[XCommon hexStringToColor:kColor_red_text] forState:UIControlStateNormal];
    _navigationBtn.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [_navigationBtn addTarget:self action:@selector(navigationBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [navigationBarView addSubview:_navigationBtn];
    
    UIButton * myChatBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    myChatBtn.frame = CGRectMake(SCREEN_WIDTH - 42.5, 26, 32, 32);
    [myChatBtn setImage:[UIImage imageNamed:@"chat_gz"] forState:UIControlStateNormal];
    [myChatBtn addTarget:self action:@selector(myChatBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [navigationBarView addSubview:myChatBtn];
    
    [self.view addSubview:navigationBarView];
    
}

#pragma mark - 跳转到我的小区
- (void)navigationBtnClick
{
    if ([SNTool shouldLoginFromController:self]) {
        return;
    }
    
    HDMyCommunityController * myCommunityVC = [[HDMyCommunityController alloc] init];
    myCommunityVC.isFirstAdd = @"2";
    myCommunityVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:myCommunityVC animated:YES];
}

#pragma mark - 点击了我的聊天
- (void)myChatBtnClick
{
    
    if ([SNTool shouldLoginFromController:self]) {
        return;
    }
    
    HDChatLIstController * chatList = [[HDChatLIstController alloc]init];
    chatList.hidesBottomBarWhenPushed = YES;
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"firstChat"]integerValue] == 0) {
        chatList.chatSign = @"0";
    }else
    {
        chatList.chatSign = @"1";
    }
    
//    if (self.isAlreadyRed == NO) {
//        chatList.tempPmids = self.pmidArr;
//    }
    
    [self.navigationController pushViewController:chatList animated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self crateNavigationBtn];
    [self refreshData];
    self.viewWillAppearCount++;
}

/** 获取navigationBtn的frame*/
- (void)crateNavigationBtn
{
    NSString * myAreaTitle = [[[NSUserDefaults standardUserDefaults] objectForKey:kMyAreaTitle] length] != 0 ? [[NSUserDefaults standardUserDefaults] objectForKey:kMyAreaTitle] : @"双明汇";
    CGFloat navigationBtnTitleW = [XCommon widthForString:myAreaTitle fontSize:15.0f] + 10;
    _navigationBtn.frame = CGRectMake((SCREEN_WIDTH - navigationBtnTitleW - 32) * 0.5, 26, navigationBtnTitleW + 40, 32);
    [_navigationBtn setTitle:myAreaTitle forState:UIControlStateNormal];
    UIImage * btnImge = [UIImage imageNamed:@"arrow_bott.png"];
    [_navigationBtn setImage:btnImge forState:UIControlStateNormal];
    _navigationBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 12 + navigationBtnTitleW, 0, 5);
    _navigationBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -10 - btnImge.size.width, 0, 2);
    self.navigationController.navigationBar.hidden = YES;
}

#pragma mark - 创建表格视图
- (void)createTabelView
{
    self.myTableView = CREATE_WITH_FRAME_OF(UITableView, CGPointMake(0, 0),
                                            [self.view.ubo fw:1.0 fh:1.0],
                                            style:UITableViewStyleGrouped);
    self.myTableView.contentInset = _myTableView.scrollIndicatorInsets =  UIEdgeInsetsMake(self.navigationAndStatusBarHeight, 0, ktabBarHeight, 0);
    self.myTableView.backgroundColor = [XCommon hexStringToColor:kColor_lightGray_cell];
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.sectionHeaderHeight = 0;
    self.myTableView.sectionFooterHeight = 0;
    self.myTableView.tableHeaderView = self.myTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.01)];
    self.myTableView.headerRefreshController = [[UIRefreshHeaderController alloc] initWithTableView:self.myTableView caller:[UBTargetCaller of:self action:@selector(refreshData)]];
    self.myTableView.nothingRefreshView = [[UIRefreshNotingRefreshView alloc] initWithView:self.myTableView viewController:self tryAgain:@selector(tryAgain)];
    [self.view addSubview:self.myTableView];
}

#pragma mark - 再试一次
- (void)tryAgain
{
    [self refreshData];
}

#pragma mark - 下拉刷新
- (void)refreshData
{
    NSString * myAreaID = [[NSUserDefaults standardUserDefaults] objectForKey:kMyAreaID] && [[[NSUserDefaults standardUserDefaults] objectForKey:kMyAreaID] length] ? [[NSUserDefaults standardUserDefaults] objectForKey:kMyAreaID] : @"0";
    
    if (self.viewWillAppearCount == 0 || ![myAreaID isEqualToString:[[SNBaseInfoManager shareManager] baseInfoObjectForKey:kLastRequestMainPageCmid]]) {//首次进入商城首页或者更换了cmid,重新加载数据.并显示转菊花
        [self.myTableView.nothingRefreshView show];
    }
    
    [self.manager loadShopPageDataWithUrl:self.uniteUrl.static_shoppageUrl withMyareaId:myAreaID];
}

#pragma mark - 首页加载数据请求完成
- (void)reloadShopPageData:(SNShopPageHttpResult *)result
{
    if (result.success) {
        
        [self.myTableView.nothingRefreshView remove];
        [self.myTableView endRefreshingAll];
        [_myTableView reloadData];
        
    } else {
        [self.myTableView.nothingRefreshView activeStop];
    }
}

#pragma mark - 商品倒计时
- (void)cellTimeChange
{
    NSArray * array = _myTableView.visibleCells;
    NSDate * nowDate = [NSDate date];
    
//    [array enumerateObjectsUsingBlock:^(SNShopMainPageView * cell, NSUInteger idx, BOOL *stop) {
//        if ([cell respondsToSelector:@selector(itemsChangeTimer:)]) {
//            [cell performSelector:@selector(itemsChangeTimer:) withObject:nowDate];
//        }
//    }];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 6;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    SNShopBaseModel * baseModel = self.result.shopModel.dataSourceArray[section];
    return baseModel.rowNumber;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        static NSString * identifier = @"brandsadCell";
        SNBrandsadCell * brandsadCell = [[SNBrandsadCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier shopBaseModel:self.result.shopModel.brandsadModel];
        brandsadCell.selectionStyle = 0;
        brandsadCell.delegate = self;
        return brandsadCell;
    } else if (indexPath.section == 1) {
        static NSString * identifier = @"activitiesIconCell";
        SNActivitiesIconCell * activitiesIconCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (activitiesIconCell == nil) {
            activitiesIconCell = [[SNActivitiesIconCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier shopBaseModel:nil];
            activitiesIconCell.selectionStyle = 0;
            activitiesIconCell.delegate = self;
        }
        [activitiesIconCell cellWithModel:self.result.shopModel.activitiesIconModel];
        return activitiesIconCell;
    } else if (indexPath.section == 2) {
        static NSString * identifier = @"noticesListCell";
        SNNoticesListCell * noticesListCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (noticesListCell == nil) {
            noticesListCell = [[SNNoticesListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier shopBaseModel:self.result.shopModel.notices_listModel row:indexPath.row];
        }
        SNShopNoticesListSubModel * subModel = self.result.shopModel.notices_listModel.notices_listArray[indexPath.row];
        [noticesListCell cellWithModel:subModel];
        noticesListCell.selectionStyle = 0;
        noticesListCell.delegate = self;
        return noticesListCell;
    } else if (indexPath.section == 3) {
        static NSString * identifier = @"themeActsListCell";
        SNThemeActsListCell * themeActsListCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (themeActsListCell == nil) {
            themeActsListCell = [[SNThemeActsListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier shopBaseModel:nil];
            themeActsListCell.selectionStyle = 0;
            themeActsListCell.delegate = self;
        }
        [themeActsListCell cellWithModel:self.result.shopModel.themeActsListModel];
        return themeActsListCell;
    } else if (indexPath.section == 4) {
        static NSString * identifier = @"activitiesListCell";
        SNActivitiesListCell * activitiesListCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (activitiesListCell == nil) {
            activitiesListCell = [[SNActivitiesListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier cellHeight:self.result.shopModel.activitiesListModel.cellHeight];
            activitiesListCell.selectionStyle = 0;
            activitiesListCell.delegate = self;
        }
        activitiesListCell.row = indexPath.row;
        activitiesListCell.shopBaseModel = self.result.shopModel.activitiesListModel;
        activitiesListCell.shopArray = self.result.shopModel.activitiesListModel.activitiesListArray[indexPath.row];
        return activitiesListCell;
    } else if (indexPath.section == 5) {
        static NSString * identifier = @"hotProductCell";
        SNHotProductCell * hotProductCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (hotProductCell == nil) {
            hotProductCell = [[SNHotProductCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier shopBaseModel:self.result.shopModel.hotProductModel row:indexPath.row];
        }
        
//         [hotProductCell createCellWithModel:self.result.shopModel.hotProductModel row:indexPath.row];
        
        DLog(@"hot____indexcpath == >>>%ld",(long)indexPath.row);
        
        SNShopHotProductSubModel * subModel = self.result.shopModel.hotProductModel.hotProductArray[indexPath.row];
        [hotProductCell cellWithModel:subModel Model:self.result.shopModel.hotProductModel Row:indexPath.row];
        hotProductCell.selectionStyle = 0;
        hotProductCell.delegate = self;
        return hotProductCell;
    } else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SNShopBaseModel * baseModel = self.result.shopModel.dataSourceArray[indexPath.section];
    return baseModel.cellHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    SNShopBaseModel * baseModel = self.result.shopModel.dataSourceArray[section];
    
    SNSectionHeaderView * sectionHeader = [[SNSectionHeaderView alloc] initWithShopModel:baseModel];
    sectionHeader.delegate = self;
    
    return sectionHeader;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    SNShopBaseModel * baseModel = self.result.shopModel.dataSourceArray[section];
    if (baseModel.headerView) {
        return kSectionHeaderViewH;
    } else {
        return 0;
    }
}

#pragma mark - 点击了 item 跳转到某个页面
- (void)itemClickWithShopBaseModel:(SNShopBaseModel *)shopBaseModel row:(NSInteger)row index:(NSInteger)index
{
    if ([shopBaseModel isKindOfClass:[SNShopBrandsadModel class]]) { //广告条幅
        
        SNShopBrandsadModel * brandsadModel = (SNShopBrandsadModel*)shopBaseModel;
        SNShopBrandsadSubModel * brandsadSubModel = brandsadModel.brandsadArray[index];
        
        if ([brandsadSubModel.ad_type isEqualToString:@"2"]) { //2,活动商品列表，跳转到某个活动的商品列表
            HZMallGoodsListViewController *mallGoodsListVC = [[HZMallGoodsListViewController alloc] init];
            
            SNShopLinkurlListModel * listModel = (SNShopLinkurlListModel *)brandsadSubModel.linkurlModel;
            
            mallGoodsListVC.actID = listModel.brand_id;
            mallGoodsListVC.actName = listModel.brand_name;
            mallGoodsListVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:mallGoodsListVC animated:YES];

        } else if ([brandsadSubModel.ad_type isEqualToString:@"4"]) { //商品详情，直接跳转到商品详情
            HZGoodsDetailViewController *detailVC = [[HZGoodsDetailViewController alloc] init];
            
            SNShopLinkurlDetailModel * detailModel = (SNShopLinkurlDetailModel *)brandsadSubModel.linkurlModel;
            
            detailVC.shopID = detailModel.shop_id;
            detailVC.productID = detailModel.product_id;
            detailVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
        
        
    } else if ([shopBaseModel isKindOfClass:[SNShopActivitiesIconModel class]]) { //广告条幅底下的小图标 : 联系物业,物业缴费,设备报修,装修申请...
        
        SNShopActivitiesIconModel * activitiesIconModel = (SNShopActivitiesIconModel*)shopBaseModel;
        SNShopActivitiesIconSubModel * activitiesIconSubModel = activitiesIconModel.activitiesIconArray[index];
        
        if ([activitiesIconSubModel.icon_type isEqualToString:@"1"]) { //链接活动
            
            HZMallGoodsListViewController *mallGoodsListVC = [[HZMallGoodsListViewController alloc] init];
            mallGoodsListVC.actID = activitiesIconSubModel.act_id;
            mallGoodsListVC.actName = activitiesIconSubModel.name;
            mallGoodsListVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:mallGoodsListVC animated:YES];
            
        } else if ([activitiesIconSubModel.icon_type isEqualToString:@"2"]) { //系统通知
            
            SNSystemNotifyController * systemNotifyVC = [[SNSystemNotifyController alloc] init];
            systemNotifyVC.titleStr = activitiesIconSubModel.name;
            systemNotifyVC.contentStr = activitiesIconSubModel.content;
            systemNotifyVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:systemNotifyVC animated:YES];
            
        } else if ([activitiesIconSubModel.icon_type isEqualToString:@"3"]) { //联系物业
            
            HDContentTenementController * opinion = [self.storyboard instantiateViewControllerWithIdentifier:@"content"];
            opinion.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:opinion animated:YES];
            
        } else if ([activitiesIconSubModel.icon_type isEqualToString:@"4"]) { //网页
            
            HZGoodsSalesViewController *salesVC = [[HZGoodsSalesViewController alloc] init];
            salesVC.hiddenNavigationItem = YES;
            salesVC.webTitle = activitiesIconSubModel.name;
            salesVC.webURL = activitiesIconSubModel.content;
            
            salesVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:salesVC animated:YES];
            
        } else if ([activitiesIconSubModel.icon_type isEqualToString:@"5"]) { //分类
            
            HZMallFindViewController * mallFindVC = [[HZMallFindViewController alloc] init];
            mallFindVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:mallFindVC animated:YES];
            
        }
        
        
    } else if ([shopBaseModel isKindOfClass:[SNShopNoticesListModel class]]) { //最新公告
        
        SNShopNoticesListModel * noticesListModel = (SNShopNoticesListModel *)shopBaseModel;
        SNShopNoticesListSubModel * noticesListSubModel = noticesListModel.notices_listArray[index];
        
        HZGoodsSalesViewController *salesVC = [[HZGoodsSalesViewController alloc] init];
        salesVC.webTitle = @"最新公告";
        salesVC.webURL = noticesListSubModel.url;
        
        salesVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:salesVC animated:YES];
        
    } else if ([shopBaseModel isKindOfClass:[SNShopThemeActsListModel class]]) { //主题市场
        
        SNShopThemeActsListModel * themeActsListModel = (SNShopThemeActsListModel *)shopBaseModel;
        SNShopThemeActsListSubModel * themeActsListSubModel = themeActsListModel.themeActsListArray[index];
        
        HZMallGoodsListViewController *mallGoodsListVC = [[HZMallGoodsListViewController alloc] init];
        mallGoodsListVC.actID = themeActsListSubModel.act_id;
        mallGoodsListVC.actName = themeActsListSubModel.name;
        mallGoodsListVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:mallGoodsListVC animated:YES];
        
    } else if ([shopBaseModel isKindOfClass:[SNShopActivitiesListModel class]]) { //推荐商家
        
        SNShopActivitiesListModel * activitiesListModel = (SNShopActivitiesListModel *)shopBaseModel;
        NSArray * array = activitiesListModel.activitiesListArray[row];
        SNShopActivitiesListSubModel * activitiesListSubModel = array[index];
        
        HZMallGoodsListViewController *mallGoodsListVC = [[HZMallGoodsListViewController alloc] init];
        mallGoodsListVC.actID = activitiesListSubModel.act_id;
        mallGoodsListVC.actName = activitiesListSubModel.name;
        mallGoodsListVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:mallGoodsListVC animated:YES];
        
    } else if ([shopBaseModel isKindOfClass:[SNShopHotProductModel class]]) { //小区爆品
        
        SNShopHotProductModel * hotProductModel = (SNShopHotProductModel *)shopBaseModel;
        SNShopHotProductSubModel * hotProductSubModel = hotProductModel.hotProductArray[index];
        
        HZGoodsDetailViewController *detailVC = [[HZGoodsDetailViewController alloc] init];
        detailVC.shopID = hotProductSubModel.shop_id;
        detailVC.productID = hotProductSubModel.product_id;
        detailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detailVC animated:YES];
        
    }
}

#pragma mark - 点击了最新公告的 更多 按钮
- (void)moreBtnInHeaderViewClick
{
    SNAllNotifyViewController * allNotifyVC = [[SNAllNotifyViewController alloc] init];
    allNotifyVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:allNotifyVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
